<?php

namespace App\Http\Controllers\WorkOrder\Web;


use App\Http\Controllers\BaseController;
use App\Models\WorkOrder\WorkOrderApplyMainModel;
use App\Service\WorkOrder\FunctionOpen\FunctionOpenZipDownloader;
use Illuminate\Http\Request;

class DownloadController extends BaseController
{
    public function zipUrl(Request $request)
    {
        $workOrderNo = (string)$request->get('workOrderNo', '');
        $m           = WorkOrderApplyMainModel::query()
            ->where('workOrderNo', $workOrderNo)
            ->first();
        if (null === $m) {
            return $this->fail(404, '工单不存在');
        }
        $downloader = new FunctionOpenZipDownloader($m);
        return $this->success([
            'url' => $downloader->zipUrl(),
        ]);
    }

    public function zipFile(Request $request)
    {
        $workOrderNo = $request->get('workOrderNo', '');
        $t           = $request->get('t', '');
        $sign        = $request->get('sign', '');
        if (abs($t - time()) > 1800) {
            return response('URL已失效，请重试', 403);
        }
        $m = WorkOrderApplyMainModel::query()
            ->where('workOrderNo', $workOrderNo)
            ->first();
        if (null === $m) {
            return response('工单不存在', 404);
        }
        $downloader = new FunctionOpenZipDownloader($m);
        $realSign   = $downloader->urlSign($workOrderNo, $t);
        if ($realSign != $sign) {
            return response('签名不正确', 403);
        }
        return $downloader->fileResponse();
    }
}
